<?php
/*--------------------------------
短信发送API

http://notice.zuitu.com/sms?user=USERNAME&pass=PASSWORD&phones=PHONES&content=CONTENT

http://notice.zuitu.com/sms?user=tzppt&pass=qq123123&phones=13559110609&content=aaa

# USERNAME：在本短信平台注册的用户名
# PASSWORD：平台登录密码MD5后的值
# PHONES：目标手机号码，多个手机号码使用半角逗号分隔，最多300个
# CONTENT：发送内容，编码建议采用UTF-8

返回 '+OK' 视为发送成功，其他内容为错误提示内容

INSERT INTO `fanwe_sms` VALUES ('0', 'Zt', '最土短信网', '', 'http://notice.zuitu.com/sms/', '', '', '', '0');
--------------------------------*/
include_once("Sms.class.php");

class ZtSms implements Sms
{

	public $message = "";
	public $smsInfo;
	
	
    public function __construct($smsInfo = '')
    { 	
		if(!empty($smsInfo))
		{
			set_time_limit(0);
			
			$this->smsInfo = $smsInfo;
		}
    }
	
	public function sendSMS($mobiles=array(),$content,$sendTime='')
	{
		$mobileLen = 300;
		$mobileList = array_chunk($mobiles,$mobileLen);
		
		$contentLen = mb_strlen($content);
		$smsTotalCount = ceil($contentLen / 160) * count($mobiles);		
		$successNum = 0;
		$code = '';
		foreach($mobileList as $mobileItem)
		{
			$mobile = implode(",",$mobileItem);
			$http = $this->smsInfo['server_url'];
			$user = $this->smsInfo['user_name'];					//用户账号
			$pass = strtolower(md5($this->smsInfo['password']));	//MD5位32密码
			$phones = $mobile;				//号码
			$content = $content;			//内容
				
			$info = urlEncode($content);
			$api = "http://notice.zuitu.com/sms?user={$user}&pass={$pass}&phones={$phones}&content={$info}";
			$res = $this->HttpRequest($api);
			//return trim(strval($res))=='+OK' ? true : strval($res);
				
			$smsLog['send_content'] = $content;
			$smsLog['action_message'] = $res;
			$sendCount = count($mobileItem);
				
			if(trim(strval($res))=='+OK')
			{
				$smsLog['success_mobiles'] = $mobile;
				$smsLog['fail_mobiles'] = "";
				$smsLog['success_count'] = $sendCount;
				$smsLog['fail_count'] = 0;
					
				$smsLog['expense_count'] = ceil($contentLen / 160) * $sendCount;

				$successNum += $sendCount;
			}
			else
			{
				$smsLog['success_mobiles'] = "";
				$smsLog['fail_mobiles'] = $mobile;
				$smsLog['success_count'] = 0;
				$smsLog['fail_count'] = $sendCount;
				$smsLog['expense_count'] = 0;
			}
				
			$smsLog['send_time'] = a_gmtTime();
				
			if(intval(a_fanweC('SMS_SEND_LOG')) == 1)
			{
				$sql = "insert into ".$GLOBALS['db_config']['DB_PREFIX']."sms_send_log (class_name,send_content,success_count,success_mobiles,fail_mobiles,expense_count,fail_count,action_message,send_time) values('Zt','".$smsLog['send_content']."','".$smsLog['success_count']."','".$smsLog['success_mobiles']."','".$smsLog['fail_mobiles']."','".$smsLog['expense_count']."','".$smsLog['fail_count']."','".$smsLog['action_message']."','".$smsLog['send_time']."')";
					
				$GLOBALS['db']->query($sql);
			}
		}
		
		if(($code == "100" && count($mobiles) == 1) || ($smsTotalCount == $successNum))
		{
			$this->message ="成功发送短信【".$content."】，到手机".implode(",",$mobiles);
			return 1;
		}
		else
		{
			$this->message = $smsTotalCount."条短信中，有".($smsTotalCount - $successNum)."条未成功发送到手机".implode(",",$mobiles);
			return 0;			
		}
	}
	
	function HttpRequest($url, $data=array(), $abort=false) {
		if ( !function_exists('curl_init') ) { return empty($data) ? $this->DoGet($url) : $this->DoPost($url, $data); }
		$timeout = $abort ? 1 : 2;
		$ch = curl_init();
		if (is_array($data) && $data) {
			$formdata = http_build_query($data);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $formdata);
		}
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		$result = curl_exec($ch);
		return (false===$result && false==$abort)? ( empty($data) ? $this->DoGet($url) : $this->DoPost($url, $data) ) : $result;
	}

	public function DoGet($url){
		$url2 = parse_url($url);
		$url2["path"] = ($url2["path"] == "" ? "/" : $url2["path"]);
		$url2["port"] = ($url2["port"] == "" ? 80 : $url2["port"]);
		$host_ip = @gethostbyname($url2["host"]);
		$fsock_timeout = 2;  //2 second
		if(($fsock = fsockopen($host_ip, $url2['port'], $errno, $errstr, $fsock_timeout)) < 0){
			return false;
		}
		$request =  $url2["path"] .($url2["query"] ? "?".$url2["query"] : "");
		$in  = "GET " . $request . " HTTP/1.0\r\n";
		$in .= "Accept: */*\r\n";
		$in .= "User-Agent: Payb-Agent\r\n";
		$in .= "Host: " . $url2["host"] . "\r\n";
		$in .= "Connection: Close\r\n\r\n";
		if(!@fwrite($fsock, $in, strlen($in))){
			fclose($fsock);
			return false;
		}
		return $this->GetHttpContent($fsock);
	}

	public function DoPost($url,$post_data=array()){
		$url2 = parse_url($url);
		$url2["path"] = ($url2["path"] == "" ? "/" : $url2["path"]);
		$url2["port"] = ($url2["port"] == "" ? 80 : $url2["port"]);
		$host_ip = @gethostbyname($url2["host"]);
		$fsock_timeout = 2; //2 second
		if(($fsock = fsockopen($host_ip, $url2['port'], $errno, $errstr, $fsock_timeout)) < 0){
			return false;
		}
		$request =  $url2["path"].($url2["query"] ? "?" . $url2["query"] : "");
		$post_data2 = http_build_query($post_data);
		$in  = "POST " . $request . " HTTP/1.0\r\n";
		$in .= "Accept: */*\r\n";
		$in .= "Host: " . $url2["host"] . "\r\n";
		$in .= "User-Agent: Lowell-Agent\r\n";
		$in .= "Content-type: application/x-www-form-urlencoded\r\n";
		$in .= "Content-Length: " . strlen($post_data2) . "\r\n";
		$in .= "Connection: Close\r\n\r\n";
		$in .= $post_data2 . "\r\n\r\n";
		unset($post_data2);
		if(!@fwrite($fsock, $in, strlen($in))){
			fclose($fsock);
			return false;
		}
		return $this->GetHttpContent($fsock);
	}
		
	private function GetHttpContent($fsock=null) {
		$out = null;
		while($buff = @fgets($fsock, 2048)){
			$out .= $buff;
		}
		fclose($fsock);
		$pos = strpos($out, "\r\n\r\n");
		$head = substr($out, 0, $pos);    //http head
		$status = substr($head, 0, strpos($head, "\r\n"));    //http status line
		$body = substr($out, $pos + 4, strlen($out) - ($pos + 4));//page body
		if(preg_match("/^HTTP\/\d\.\d\s([\d]+)\s.*$/", $status, $matches)){
			if(intval($matches[1]) / 100 == 2){
				return $body;  
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
}
?>